package com.colmmcsky.twit2lj;

import java.util.Calendar;

import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

//Update the output when the extraction is done
public class LogUpdater extends Handler {
	private TextView mStatus;
	private SharedPreferences mPreferences;
	
	public LogUpdater(SharedPreferences preferences, TextView status) {
		mStatus = status;
		mPreferences = preferences;

    	String logString = mPreferences.getString(MainActivity.LogKey, "");     	
		
		if (mStatus != null) {
			mStatus.setText(logString);
		}	
	}

    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    
	public void handleMessage(Message message) {
    	String logString = mPreferences.getString(MainActivity.LogKey, "");     	
		
		String text = (String) message.obj;

		// note the current date/time
		Calendar now = Calendar.getInstance();
		
		int year = now.get(Calendar.YEAR);
		int month = now.get(Calendar.MONTH);
		int day = now.get(Calendar.DAY_OF_MONTH);
		int hour = now.get(Calendar.HOUR_OF_DAY);
		int min = now.get(Calendar.MINUTE);
		int sec = now.get(Calendar.SECOND);
		
		String timestamp = "" 
				+ year + "-"
				+ (1+month) + "-"
				+ day + " "
				+ pad(hour) + ":"
				+ pad(min) + ":"
				+ pad(sec) + " - ";

		logString = timestamp + text + "\n" + logString;	
		
		int maxLength = 1024;
		if (logString.length() > maxLength) {
			logString = logString.subSequence(0, maxLength).toString();
		}
				
		SharedPreferences.Editor editor = mPreferences.edit();
		
		editor.putString(MainActivity.LogKey, logString);
		editor.commit();
 	
		if (mStatus != null) {
			mStatus.setText(logString);
		}			
	}
}
